<?php


namespace Database\Seeders;

use App\Models\Pdf\PdfImageCoordinate;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Models\Pdf\PdfImage;

class PdfDataSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        try {
            $pdfs = DB::connection('zjmysql')->table('pdfs')->select(['id', 'name'])->get()->toArray();
            $pdfs = json_decode(json_encode($pdfs), true);

            foreach ($pdfs as $pdf) {
                $categoryId = DB::connection('zjmysql')->table('categorys')->where('name', $pdf['name'])->value('id');
                $pdfImages = DB::connection('zjmysql')->table('pdf_images')->where('pdf_id', $pdf['id'])->get()->toArray();
                $pdfImages = json_decode(json_encode($pdfImages), true);

                if ($categoryId != null && $categoryId != '') {
                    foreach ($pdfImages as $image) {
                        $image['category_id'] = $categoryId;
                        unset($image['pdf_id']);
                        PdfImage::query()->updateOrCreate(['id' => $image['id']], $image);

                        $image_coordinates = DB::connection('zjmysql')->table('pdf_image_coordinates')->where('pdf_image_id', $image['id'])->get()->toArray();
                        $image_coordinates = json_decode(json_encode($image_coordinates), true);

                        foreach ($image_coordinates as $image_coordinate) {
                            PdfImageCoordinate::query()->updateOrCreate(['id' => $image_coordinate['id']], $image_coordinate);
                        }
                    }
                }
            }

            $this->command->info('教材点读数据填充完成！');
        } catch (\Exception $e) {
            $this->command->error('教材点读数据填充失败: ' . $e->getMessage());
            $this->command->warn('请检查 zjmysql 数据库连接配置是否正确');
        }
    }
}
